package com.qmth.gkwb.data.sync;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.qmth.gkwb.data.constant.OrderStatus;
import com.qmth.gkwb.data.document.Order;
import com.qmth.gkwb.data.document.Student;
import com.qmth.gkwb.data.repository.OrderRepo;
import com.qmth.gkwb.data.repository.StudentRepo;
import com.qmth.gkwb.data.repository.ZFZFDRepo;
import com.qmth.gkwb.data.repository.ZFZFMXRepo;

/**
 * 定时同步任务
 * @author zhengmin
 *
 */
@Component
public class SyncSchedule {

	private Logger logger = LoggerFactory.getLogger(SyncSchedule.class);

	@Autowired private StudentRepo studentRepo;
	@Autowired private SyncService syncService;
	@Autowired private ZFZFDRepo zfdRepo;
	@Autowired private ZFZFMXRepo zfmxRepo;
	@Autowired private OrderRepo orderRepo;
	@Autowired private Environment env;
	
	@Scheduled(cron="${app.sync.cron}")
	public void studentTask(){
		String enabled = env.getProperty("app.sync.enabled");
		if(enabled.equals("true")){
		int totalCount = studentRepo.countByIsSycAndSycFail(false, false);
		if(totalCount > 0){
			logger.info("===========开始执行考生报名信息同步===========");
			logger.info("需要同步的总数："+totalCount);
			int pageSize = 100;
			int pageCount = (int)totalCount/pageSize;
			if(totalCount%pageSize > 0)
			     pageCount++;
			int synced = 0;
			for(int i = 0 ; i < pageCount; i++){
				Pageable p = new PageRequest(i, pageSize);
				List<Student> students = studentRepo.findByIsSycAndSycFail(false, false, p); 
				for(Student student : students){
					try {
						boolean result = syncService.syncStudent(student);
						if(result){
							synced++;
							//更新考生同步状态为true
							student.setIsSyc(true);
						}
						
					} catch (Exception e) {
						student.setSycFail(true);
						logger.error(student.getExamId()+"同步失败");
						e.printStackTrace();
					}finally{
						studentRepo.save(student);
						
					}
				}
				logger.info("已同步"+synced+"条信息");
			}
			logger.info("总同步"+synced+"条数据");
			logger.info("===========考生报名信息同步完毕===========");
		}
		int orderCount = orderRepo.countByIsSyncAndSyncFailAndStatus(false, false, OrderStatus.COMPLETE);
		if(orderCount > 0){
			logger.info("===========开始订单d同步===========");
			logger.info("需要同步的总数："+orderCount);
			int pageSize = 100;
			int pageCount = (int)orderCount/pageSize;
			if(orderCount%pageSize > 0)
			     pageCount++;
			Long zfdMaxId = zfdRepo.findMaxId();
			Long zfmxMaxId = zfmxRepo.findMaxId();
			long zfdId =  zfdMaxId == null?100000:zfdMaxId;
			long zfmxId = zfmxMaxId == null?100000:zfmxMaxId;
			int orderSynced = 0;
			for(int i = 0 ; i < pageCount; i++){
				Pageable p = new PageRequest(i, pageSize);
				List<Order> orders = orderRepo.findByIsSyncAndSyncFailAndStatus(false, false, OrderStatus.COMPLETE, p);
				for(Order order : orders){
					zfdId++;
					zfmxId++;
					try{
						boolean result = syncService.syncOrders(order, zfdId, zfmxId);
						if(result){
							orderSynced++;
							order.setSync(true);
							
						}
						
					}
					catch(Exception e){
						order.setSyncFail(true);
						logger.error(order.getOrderId()+"同步失败:"+e.getMessage());
					}
					finally{
						orderRepo.save(order);
					}
				}
				logger.info("已同步"+orderSynced+"条信息");
			}
			logger.info("总同步"+orderSynced+"条数据");
			
			logger.info("===========订单同步完毕===========");
		}
		}
	}
}
